const request = require('request')
const pinyin = require('tiny-pinyin')
const _ = require('lodash')
const { baseUrl } = require('./config')
/**
 *
 * saveHandle
 * @param url
 * @param {request.jar} jar
 * @param {object} arg
 * @param {function} cb
 * @returns {status: 'success'}
 */
module.exports = (arg, patient, jar, cb) => {
  if (patient === null) return
  if (arg.type === 'medicines') {
    const { medicines } = patient
    const drugs = []
    let group = 0
    let price = 0
    for (let k = 0; k < medicines.rows; k += 1) {
      if (medicines[`group_${k}`] === false) {
        group += 1
      }
      if (medicines[`times_${k}`] === undefined) return
      if (medicines[`usage_${k}`] === undefined) return
      drugs.push({
        drug: medicines[`drug_${k}`],
        group: group,
        count: medicines[`count_${k}`],
        days: medicines[`days_${k}`],
        dose: medicines[`dose_${k}`],
        doseunit: medicines[`doseunit_${k}`],
        postfix: medicines[`postfix_${k}`],
        price: medicines[`price_${k}`],
        times: medicines[`times_${k}`].value || '',
        usage: medicines[`usage_${k}`].value || '',
      })
      price += parseFloat(medicines[`price_${k}`])
    }
    if (patient.state === undefined) return
    if (patient.state.fullname === undefined) return
    if (patient.state.depart === undefined) return
    if (patient.state.doctor === undefined) return
    let p = patient.state.ID
    if (p === undefined) {
      let py = ''
      if (pinyin.isSupported()) {
        _.forEach(patient.state.fullname.label, (word) => {
          py += pinyin.convertToPinyin(word).substr(0, 1).toLocaleLowerCase()
        })
      }
      p = {
        name: patient.state.fullname,
        py: py,
        gender: patient.state.gender && patient.state.gender.label || '男',
        age: patient.state.age,
        weight: patient.state.weight || '',
      }
    }
    const prescription = {
      drugs: drugs,
      price: price,
      diagnosis: patient.state.diagnosis || '',
      patient: p,
      depart: patient.state.depart.label,
      doctor: patient.state.doctor.label,
    }
    request.put({
      url: `${baseUrl}api/prescription`,
      jar: jar,
      form: {
        prescription: JSON.stringify(prescription)
      }
    }, (err, httpResponse, body) => {
      console.log(body)
      cb(body)
    })
  }
}